import React from 'react'
import {Row, Col, Button, Table, Select, Input, Avatar, Modal, message,Checkbox} from 'antd'
// import { UserOutlined } from '@ant-design/icons';
import './styles.css'
import Model from "./Model"
import api from "../../../api/api";
import axios from 'axios';


const {Search} = Input;
const {Option} = Select;


class Reserve extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            modelData: {
                title: "新增人员",
                visible: false,
                type: 1,//新增人员:1,添加 2,编辑
                gridList: {},

            },
            title: "预定信息管理",
            visible: false,
            data: [],
            selectCompanyId: undefined,
            selectFactoryId: undefined,
            selectDepartmentId: undefined,
            identifySelectId:undefined,
            userType: undefined,
            pageNum: 1,
            pageSize: 10,
            total: 0,
            selectedRowIds:[],
            setIdentify:"1",
            identityFlagPerson:"",//5代表没有身份
            hiddenFlag:true,
            reserveName:undefined,
            reservePhone:undefined,

        };
    }

    componentDidMount() {
        this.getRoomManagerList();
        this.companyChange();
        this.getuserTypeSelect();
        this.getidentifySelect();
      }
   columns = [
       {
           title: 'id',
           dataIndex: 'id',
           className: "elementHidden",
           key: 'id',
           width: 'auto'
       },
       {
           title: '客户姓名',
           dataIndex: 'reserveName',
           key: 'reserveName',
           width: 'auto'
       },
        {
            title: '手机号',
            dataIndex: 'reservePhone',
            width: 'auto',
            key: 'reservePhone'
        },
        {
            title: '订单时间',
            dataIndex: 'createTime',
            width: 'auto',
            key: 'createTime'
        },
        {
            title: '房间号',
            dataIndex: 'reserveRoom',
            width: 'auto',
            key: 'reserveRoom'
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '20%',
            key: 'option',
            render: (_ext, record, Item) => {
                return (
                <span>
                      <a className="optionMargin" onClick={() => this.onClickEdit(record)}>编辑</a>
                      <a className="optionMargin" onClick={() => this.onClickDelete(record.userId)}>删除</a>
                </span>
                        )

            }
        }
    ];


    getRoomManagerList() {
        let that = this;
        axios.post(api.api_URL + "/reserve/selectAllReserveMessage?pageNum=" + this.state.pageNum + "&pageSize=" + this.state.pageSize, {
            reserveName:this.state.reserveName,
            reservePhone:this.state.reservePhone

        }, {
            headers: {
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            console.info(res.data)
            if (res.data.errorCode != 1) {
                return;
            }
            let totalSize = res.data.object.size;
            const dataList = [];
            for (let i = 0; i < res.data.object.records.length; i++) {
                let resContent = res.data.object.records[i];
                const content = {};
                content.key = (i + 1);
                content.id = resContent.id;
                content.reserveName = resContent.reserveName;
                content.reservePhone = resContent.reservePhone;
                content.reserveRoom = resContent.reserveRoom;
                let date = Date.parse(resContent.createTime);
                content.createTime=new Date(date).toLocaleString();
                dataList[i] = content;
            }

            that.setState({
                data: dataList,
                total: totalSize
            })
        }).catch(function (err) {
           // console.log(err);
        });
    }


//分页
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getRoomManagerList()
        });

    }

    onclickSearch() {
        console.info("搜索");
        this.getRoomManagerList();
    }
    identifySelect=[]
    getidentifySelect(){
        let that = this;
        that.identifySelect.push(<Option key="0">普通用户</Option>);
        that.identifySelect.push(  <Option key="1">门岗</Option>);
        that.identifySelect.push(<Option key="2">审核人员</Option>);

    }
    //获取公司下拉框值
    companySelect = [];

    getCompanySelect() {
        let that = this;
        let dataList = [];
        let url = api.api_URL + "/admin/company/queryAllCompanyInfoForSelect?orgCode="+localStorage.getItem("orgCode");
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            let companyInfoList = res.data.data.companyInfoList;
            for (let i = 0; i < companyInfoList.length; i++) {
                let comData = companyInfoList[i];
                const data = {};
                data.key = comData.thirdCompanyId;
                data.label = comData.companyName;
                dataList[i] = data;
            }
            for (let i = 0; i < dataList.length; i++) {
                that.companySelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);

            }

        }).catch(function (err) {
            message.error({content:"加载失败，请重新尝试！"})
            console.log(err);
        })

    }

    //获取部门下拉框值
    departmentSelect = [];

    //选择公司
    companyChange = () => {
        this.factorySelect = [];
        this.departmentSelect = [];
        let that = this;
        let dataList = [];
        let url;
      //  url= api.api_URL + "/admin/factory/queryFactoryInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            let factoryInfoList = res.data.data.factoryInfoList;
            if (factoryInfoList.length <= 0) {
                console.log("没有公司数据")
                return;
            }
            for (let i = 0; i < factoryInfoList.length; i++) {
                let facData = factoryInfoList[i];
                const data = {};
                data.key = facData.thirdFactoryId;
                data.label = facData.name;
                dataList[i] = data;
            }
            for (let i = 0; i < dataList.length; i++) {
                that.factorySelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }
        }).catch(function (err) {
           // console.log(err);
        })

    }



        departmentChange = (value) => {
            this.setState({
                selectDepartmentId: value
            })
        }

        inputName = (e) => {
            console.log(e.target.value)
            this.setState({
                reserveName: e.target.value
            })
        }
        inputPhone = (e) => {
            console.log(e.target.value)
            this.setState({
                reservePhone: e.target.value
            })
        }



//删除
    onClickDelete(item) {
        console.info("删除===", item);
        let that = this;
        let configModel = Modal.confirm({
            title: '删除',
            content: '是否确认删除？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    let url = api.api_URL + "/admin/visituserinfo/deleteVisitUserInfo?visitUserInfoId=" + item + "&orgCode=" + localStorage.getItem("orgCode");
                    axios.get(url, {
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": api.ContentType
                        }
                    }).then(function (res) {
                        if (res.data.code != 1) {
                            message.error({content:"删除失败，请重新尝试！"})
                            return;
                        }
                        message.success({content:"删除成功！"})

                        that.setState({
                            data: []
                        })
                        that.getRoomManagerList();
                        configModel.destroy();

                    }).catch(function (err) {
                        message.error({content:"删除失败，请重新尝试！"})

                        console.log(err);
                    })
                }).catch((e) => console.warn(e));
            },
            onCancel() {
            },
        })
    }

//编辑
    onClickEdit(item) {
        this.setState({
            modelData: {
                title: "编辑",
                type: 2,
                visible: true,
                gridList: item,

            }
        }, () => {
            this.child.initEditData()
        });
    }

    //添加
    addPersion() {
        this.setState({
            modelData: {
                title: "新增人员",
                type: 1,
                visible: true
            }
        }, () => {
            this.child.clearData()
        });
    }

    onclickReset() {
        this.departmentSelect=[]
        this.setState({
           selectFactoryId: undefined,
            selectDepartmentId: undefined,
            userType: undefined,
            identifySelectId:undefined,
            reserveName:undefined,
            reservePhone:undefined
        },() => {
            this.getRoomManagerList()
        });

    };

    handleOk = e => {
        console.log(e);
        this.setState({
            visible: false,
        });
    };
    handleOkForIdentify= e =>{
        let that=this;
        if (this.state.setIdentify=="2" && this.state.identityFlagPerson=="" ){
            alert("请选择审核人员身份")
        }else {
            let url = api.api_URL + "/admin/visituserinfo/setPersonIdentify";
            axios.post(url, {
                "userId":this.state.selectedRowIds,
                "identityFlag": this.state.setIdentify,
                "identityFlagPerson": this.state.identityFlagPerson,

            },{
                headers: {
                    "Authorization": localStorage.getItem('token'),
                    "Content-Type": api.ContentType
                }
            }).then(function (res) {
                that.handleCancel()
                if (res.data.code==1) {
                    message.success({content:"身份设置成功！"})
                }else{
                    message.error({content:"身份设置失败！"})
                }
                that.setState({
                    setIdentify: "1"
                })
            }).catch(function (err) {
                console.log(err);
            });
            that.setState({
                identityFlagPerson: "",
                selectedRowIds:[],
                hiddenFlag:true,
                identifySelectId:undefined,
                c1:false,
                c2:false,
            })
        }

    }
    identifyChange=(value)=>{
        let that=this;
        this.setState({
            setIdentify: value,
            identifySelectId: value,
        })
        if (value==2||value=="2"){
            that.setState({
                hiddenFlag: false
            })
        }else {
            that.setState({
                hiddenFlag: true
            })
        }
    }
    handleCancel = e => {
        this.setState({
            visible:false,
            hiddenFlag:true,
            modelData: {
                visible: false
            },
        }, () => {
            this.refresh()
        });

    }


    //获取用户类型下拉框值
    userTypeSelect = [];

    getuserTypeSelect() {
        let data = [
            {key: "0", label: "普通用户"},
            {key: "1", label: "门岗"},
            {key: "2", label: "审核管理员"},
        ]
        for (let i = 0; i < data.length; i++) {
            this.userTypeSelect.push(<Option key={data[i].key}>{data[i].label}</Option>);
        }
    }

    userTypeChange = (value) => {
        this.setState({
            userType: value
        })
    }

    refresh() {
        this.getRoomManagerList()
    }

    onRef = (ref) => {
        this.child = ref
    }

    c1=(value)=> {
        console.log(value.target.checked)
        this.setState({
            c1:value.target.checked
        })
    }
    c2=(value)=> {
        console.log(value.target.checked)
        this.setState({
            c2:value.target.checked
        })
    }

    render() {
        const {selectedRowKeys } = this.state;
        const CheckboxGroup = Checkbox.Group;
        const CheckBox=Checkbox;
        let { c1, c2} = this.state
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys) => {
                this.setState({
                    selectedRowIds : selectedRowKeys.map(Number),
                    selectedRowKeys
                })
                console.log(`selectedRowKeys: ${selectedRowKeys}`);
                console.log(this.state.selectedRowIds)
            },
        };
        return (
            <div className="girdBg">
                <Row className="searchBox">
                    <Col span={18}>
                        <Search style={{width: 250,marginLeft:30}}
                                placeholder="请输入电话" onChange={this.inputPhone}  allowClear value={this.state.reservePhone}
                        />
                        <Search style={{width: 250,marginLeft:30}}
                                placeholder="请输入姓名" onChange={this.inputName}  allowClear value={this.state.reserveName}
                        />
                    </Col>
                    <Col span={6} className="btnRight">
                        <Button icon={"save"} type='primary' onClick={this.addPersion.bind(this)}>新增预订信息</Button>
                    </Col>
                </Row>
                <Row className="searchBox">
                    <Col span={18}>
                        <Button icon={"search"} type='primary' style={{marginLeft: 30}}
                                onClick={this.onclickSearch.bind(this)}>搜索</Button>
                        <Button icon={"reset"} style={{marginLeft: 30}} onClick={this.onclickReset.bind(this)}>重置</Button>
                    </Col>
                </Row>
                <Row style={{margin: 30}}>
                    <Table
                        columns={this.columns}
                        dataSource={this.state.data}
                        scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                        rowSelection={rowSelection}
                        rowKey={record =>record.userId}
                        columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                            const fun = () => ({style: {whiteSpace: 'nowrap'}});
                            item.onHeaderCell = fun;
                            item.onCell = fun;
                            return item;
                        })}
                        pagination={{
                            simple: false,
                            current: this.state.pageNum,
                            total: this.state.total,
                            pageSize: this.state.pageSize,
                            showTotal: (count = this.state.total) => {
                                return '共' + count + '条'
                            },
                            onChange: (current, pageSize) => {
                                this.onBaseClick(current, pageSize)
                            }
                        }}
                    />
                </Row>
                <Model data={this.state.modelData} handleCancel={this.handleCancel} refresh={this.refresh}
                       onRef={this.onRef} history={this.props.history}/>
                <Modal title="设置身份信息"refresh={this.refresh}
                       visible={this.state.visible}
                       onOk={this.handleOkForIdentify}
                       onCancel={this.handleCancel}

                >
                    <p/>
                   <div hidden={this.state.hiddenFlag}>
                    <Select style={{width: 300}}  placeholder="请选择角色"  onChange={this.identityFlagPersonChange}>
                        <Option key="1">室主任/作业长</Option>
                        <Option key="2">部门长</Option>
                        <Option key="3">公司领导</Option>
                        <Option key="4">访问审核</Option>
                    </Select>
                    </div>
                </Modal>
            </div>
        )
    }
}

export default Reserve
